<template>
  <div>
    <el-row class="certificate-title">
      <el-col :span="12">
        <span class="two-level-title">{{ title }}</span>
      </el-col>
      <el-col v-if="edit === '1'" :span="12" class="right">
        <el-dropdown @command="handleAdd">
          <el-button type="primary" class="add" icon="el-icon-plus" size="mini" plain>新增 <i class="el-icon-arrow-down " /></el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-for="(item,index) in addCertList" :key="item.id" :command="index">{{ item.certificateName }}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
    </el-row>
    <div class="certificate-list">
      <el-form label-width="auto" :model="formData">
        <el-row :gutter="20">
          <el-col v-if="sysEnterpriseType === '03' || sysEnterpriseType === '04'" :lg="12">
            <div class="cert-item cert-item-add right">
              <div v-if="fixedCertificateReadOnly" class="addSave">
                <span @click="handleEditFixed">编辑</span>
              </div>
              <div v-else class="addSave">
                <span @click="addCancelFixed">取消</span>
                <span @click="addSaveFixed">保存</span>
              </div>
              <el-row :gutter="20">
                <el-col :span="8" class="certificate-list-upload">
                  <ImgUploadOne :is-mark="fixedCertificateReadOnly" :edit-file-list="certifileList" @getFilePic="getCertifileList" />
                </el-col>
                <el-col :span="16">
                  <el-form-item prop="certificateNum" label="证书编号">
                    <el-input v-model="fixedCertificateForm.certificateNum" :readonly="fixedCertificateReadOnly" size="small" placeholder="请输入证书编号" />
                  </el-form-item>
                  <el-form-item prop="validUntil" label="">
                    <label slot="label" v-html="`有&ensp;效&ensp;期`" />
                    <el-date-picker v-model="fixedCertificateForm.validUntil" :readonly="fixedCertificateReadOnly" value-format="yyyy-MM-dd" style="width:100%;" size="small" type="date" placeholder="请选择证书资质有效期" />
                  </el-form-item>
                  <el-form-item prop="qualificationLevel" label="资质等级">
                    <el-select v-model="fixedCertificateForm.qualificationLevel" :disabled="fixedCertificateReadOnly" size="small" clearable style="width:100%;" placeholder="请选择资质等级">
                      <el-option
                        v-for="item in proGrade"
                        :key="item.dictValue"
                        :label="item.dictLabel"
                        :value="item.dictValue"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
          <el-col v-if="isSave" :lg="12">
            <div class="cert-item cert-item-add">
              <div class="addSave">
                <span @click="addCancel">取消</span>
                <span @click="addSave">保存</span>
              </div>
              <el-row :gutter="20">
                <el-col :span="8" class="certificate-list-upload">
                  <ImgUploadOneC
                    :cert-id="certId"
                    :edit-file-list="formData.appFiles"
                    @getCertData="getCertData"
                    @click.native="handleId(formData.id)"
                    @getFilePic="formData.appFilePic = $event"
                  />
                </el-col>
                <el-col :span="16">
                  <el-form-item v-for="(label, i) in formData.detailList" :key="i" :label="label.fieldName">
                    <el-input :ref="`newInput${i}`" v-model="label.value" size="small" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
          <el-col
            v-for="(item,index) in cloneCertList"
            :key="index"
            :lg="12"
          >
            <div class="cert-item">
              <h3>
                <span>{{ item.certificateName }}</span>
                <div v-if="edit === '1'" class="right">
                  <div v-if="item.isEdit" class="edit" @click="handleEdit(index,item)">编辑</div>
                  <div v-else class="save">
                    <span @click="handleCancel(index)">取消</span>
                    <span @click="handleSave(index,item)">保存</span>
                  </div>
                </div>
              </h3>
              <el-row :gutter="20">
                <el-col :span="8" class="certificate-list-upload">
                  <ImgUploadCert :is-mark="item.isEdit" :edit-file-list="item.fileId" @getFilePic="item.fileId = $event" />
                </el-col>
                <el-col :span="16">
                  <el-form-item v-for="(label, i) in item.certificateVal" :key="i" :label="label.fieldName ">
                    <!--                    <span v-show="item.isEdit" class="desc">{{ label.value }}</span>-->
                    <el-input
                      :ref="`input${index}`"
                      v-model="label.value"
                      :readonly="item.isEdit"
                      size="small"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
// 证书图片
import ImgUploadOneC from '@/components/Upload/ImgUploadOneC'
import ImgUploadOne from '@/components/Upload/ImgUploadOne'
import ImgUploadCert from '@/components/Upload/ImgUploadCert'
import { mapState } from 'vuex'
export default {
  name: 'CertificateList',
  components: {
    ImgUploadCert,
    ImgUploadOneC,
    ImgUploadOne
  },
  props: {
    // 企业类型
    sysEnterpriseType: {
      type: String,
      default: ''
    },
    fixedCertificate: {
      type: Object,
      default: () => {
      }
    },
    title: {
      type: String,
      default: ''
    },
    edit: {
      type: String,
      default: ''
    },
    certList: {
      type: Array,
      default: () => []
    },
    addCertList: {
      type: Array,
      default: () => []
    }

  },
  data() {
    return {
      fixedCertificateReadOnly: true, // 固定证书只读
      certifileList: [], // 固定证书
      qualificationUrl: '', // 固定的证书id
      fixedCertificateFormOld: {}, // 固定的证书表单修改前的旧数据
      fixedCertificateForm: { // 固定的证书表单
        certificateNum: '',
        validUntil: '',
        qualificationLevel: ''
      },
      certId: '',
      cloneCertList: [],
      // 编辑前的状态
      lastlCert: {},
      // 新增表单
      isSave: false,
      formData: {}
    }
  },
  computed: {
    ...mapState({
      proGrade: state => state.basicInfo.proGrade // 项目等级
    }),
    isEditCert() {
      return this.checkEditStatus()
    }
  },
  watch: {
    certList(values) {
      this.cloneCertList = values.map((item) => {
        const { id, certificateId, certificateVal, companyCertificate: { certificateName }, fileId } = item
        return {
          id, fileId, certificateId, certificateName,
          certificateVal: JSON.parse(certificateVal), isEdit: true
        }
      })
    },
    fixedCertificate(val, oldVal) {
      if (val === oldVal) return
      this.certifileList = [{ fileId: val.qualificationUrl }]
      this.fixedCertificateForm = val
      this.fixedCertificateFormOld = JSON.stringify(val)
    }
  },
  methods: {
    /** 固定证书 start*/
    // 固定的资质证书
    getCertifileList(fileList) {
      console.log(2)
      this.fixedCertificateForm.qualificationUrl = fileList[0].fileId
    },
    // 编辑
    handleEditFixed() {
      this.fixedCertificateReadOnly = false
    },
    // 取消
    addCancelFixed() {
      this.fixedCertificateReadOnly = true
      this.fixedCertificateForm = JSON.parse(this.fixedCertificateFormOld)
    },
    // 保存
    addSaveFixed() {
      this.fixedCertificateReadOnly = true
      this.$emit('updateFixed', { ...this.fixedCertificateForm })
    },
    /** 固定证书 end*/

    /** 动态证书 start*/
    // 获取动态证书
    getCertData(data) {
      this.formData.detailList.forEach(item => {
        this.$set(item, 'value', '')
      })
      for (const k in data) {
        const item = this.formData.detailList.find(item => item.fileVal === k)
        if (item) {
          this.$set(item, 'value', data[k])
        }
      }
    },
    handleId(certId) {
      this.certId = certId
    },
    // 切换编辑
    handleEdit(index, item) {
      // 检测是否处于编辑状态
      const isCheck = this.checkEditStatus()
      if (isCheck) return

      // 深拷贝给取消使用
      this.lastlCert = JSON.parse(JSON.stringify(item))

      // 切换为保存
      item.isEdit = false

      // 视图更新后获取焦点
      this.$nextTick(() => {
        const [first] = this.$refs[`input${index}`]
        first.focus()
      })
    },
    // 保存更改
    handleSave(index, item) {
      // 处于编辑的input
      const isCheck = this.checkNullValue(index)
      // 校验表单项
      if (isCheck) {
        this.msgWarning('证书附件或信息不能为空!')
        return
      }
      // 编辑成功
      item.isEdit = true
      // 数据处理
    },
    // 取消编辑
    handleCancel(index) {
      // 还原编辑前的状态
      this.cloneCertList.splice(index, 1, this.lastlCert)
    },
    // 校验是否有值为空
    checkNullValue(index) {
      const inputs = this.$refs[`input${index}`]
      const isCheck = inputs.some((element) => {
        const v = element.value
        if (v === undefined) {
          return false
        } else {
          return v === null || v.trim() === ''
        }
      })
      return isCheck
    },
    // 检测编辑状态
    checkEditStatus() {
      //  校验一
      if (this.isSave || !this.fixedCertificateReadOnly) {
        this.msgWarning('请先保存新增的证书!')
        return true
      }
      // 校验二
      const isCheck = this.cloneCertList.some((item) => !item.isEdit)
      if (isCheck) {
        this.msgWarning('请先保存处于编辑的证书!')
        return true
      }
    },
    // 新增按钮
    handleAdd(command) {
      const isCheck = this.checkEditStatus()
      if (isCheck) return

      this.isSave = true
      // 获取新增证书的信息
      const newCert = this.addCertList[command]
      newCert['isEdit'] = false
      newCert.fileId = newCert.appFiles[0].fileId
      this.formData = JSON.parse(JSON.stringify(newCert))
      // 获取第一个input焦点
      this.$nextTick(() => {
        this.$refs.newInput0[0].focus()
      })
    },
    // 新增保存
    addSave() {
      const isCheck = this.formData.detailList.some((item) => {
        if (item.value === undefined) {
          return false
        } else {
          return item.value === null || item.value.trim() === ''
        }
      })
      if (isCheck) {
        this.msgWarning('证书附件或信息不能为空!')
        return
      }
      this.isSave = false

      // 改变对象的引用地址
      const certList = [this.formData].map(cert => {
        const { id, fileId, detailList, certificateName } = cert
        const certificateVal = detailList.map(item => {
          const { fieldName, fileVal, value, isRemind } = item
          return { fieldName, fileVal, value, isRemind }
        })
        return { certificateName, certificateId: id, fileId, certificateVal, isEdit: true }
      })
      this.cloneCertList.push(certList[0])
      // 重置表单
      this.formData = {}
    },
    // 新增取消
    addCancel() {
      this.isSave = false
      this.formData = {}
    }
    /** 动态证书 end*/
  }
}
</script>

